<template>
  <div
    class="data-analysis custom-el-plus"
    element-loading-background="rgba(0,0,0,0.5)">
    <div class="search-wrapper">
      <el-form
        ref="ruleFormRef"
        :model="queryForm"
        :rules="queryRules"
        inline>
        <el-form-item
          label="行政区划"
          prop="regionArea">
          <el-cascader
            v-model="queryForm.regionArea"
            :options="regionList"
            popper-class="custom-query-select"
            :props="elProps"
            :show-all-levels="false"
            clearable />
        </el-form-item>
        <el-form-item
          label="日期范围"
          prop="dateRange">
          <el-date-picker
            v-model="queryForm.dateRange"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="至"
            @calendar-change="changeRange"
            @change="clearDateArray"
            :disabled-date="disabledDate"
            start-placeholder="开始日期"
            end-placeholder="结束日期" />
        </el-form-item>
        <el-form-item
          label="事件类型"
          prop="eventType">
          <el-select
            multiple
            collapse-tags
            collapse-tags-tooltip
            v-model="queryForm.eventType"
            popper-class="custom-query-select">
            <template #header>
              <el-checkbox
                v-model="checkAll"
                :indeterminate="indeterminate"
                @change="handleCheckAll">
                全部
              </el-checkbox>
            </template>
            <el-option
              v-for="item in eventTypeList"
              :key="item.pkId"
              :label="item.alarmType"
              :value="item.pkId">
              <span class="check"></span>
              <span style="margin-left: 8px">{{ item.alarmType }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="btn-group">
        <el-button
          style="margin-left: auto"
          type="primary"
          @click="queryAllData(ruleFormRef)"
          :disabled="loadingStatus || tableLoadingStatus"
          >搜索</el-button
        >
        <el-button
          type="primary"
          @click="exportData"
          :disabled="exportLoading"
          v-if="activeMenuIndex === 1 && detailListData?.list?.length"
          >导出</el-button
        >
      </div>
    </div>
    <div
      class="main-content-wrapper"
      :style="{ overflowY: activeMenuIndex === 1 ? 'inherit' : 'scroll' }">
      <div class="menu-bar">
        <div
          class="menu-item"
          :class="{ 'menu-active': index === activeMenuIndex }"
          v-for="(item, index) in menuList"
          :key="index"
          @click="handleMenuClick(item, index)">
          {{ item }}
        </div>
      </div>
      <DataStatistical
        v-if="activeMenuIndex === 0"
        :rankList="rankList"
        :timeHeatMapData="timeHeatMapData"
        :spaceHeatMapData="spaceHeatMapData"
        :eventComparisonList="eventComparisonList"></DataStatistical>
      <DataDetailList
        v-if="activeMenuIndex === 1"
        :loading="tableLoadingStatus"
        :detailListData="detailListData"
        @changePageNum="changePageNum"
        @changePageSize="changePageSize"></DataDetailList>
    </div>
  </div>
</template>

<script setup>
  import { getCurrentInstance, onMounted, reactive, ref, watch } from 'vue'
  import DataStatistical from './components/dataStatistical.vue'
  import DataDetailList from './components/dataDetailList.vue'

  const { proxy } = getCurrentInstance()
  const elProps = {
    expandTrigger: 'hover',
    checkStrictly: true
  }
  const ruleFormRef = ref(null)
  const pageInfo = reactive({
    pageNum: 1,
    pageSize: 15
  })
  const regionList = ref([])
  const queryForm = reactive({
    regionArea: '',
    dateRange: [proxy.$moment(new Date().getTime() - 1000 * 60 * 60 * 24 * 8).format('YYYY-MM-DD'), proxy.$moment(new Date().getTime() - 1000 * 60 * 60 * 24).format('YYYY-MM-DD')],
    eventType: []
  })
  const queryRules = reactive({
    regionArea: [{ required: true, message: '请选择地区', trigger: ['blur', 'change'] }],
    dateRange: [{ required: true, message: '请选择日期', trigger: ['blur', 'change'] }],
    eventType: [{ required: true, message: '请选择事件类型', trigger: ['blur', 'change'] }]
  })
  const eventTypeList = ref([])
  const rankList = ref([])
  const eventComparisonList = ref([])
  const detailListData = ref([])
  const menuList = ['统计分析', '数据详单']
  const activeMenuIndex = ref(0)
  const loadingStatus = ref(false)
  const tableLoadingStatus = ref(false)
  const spaceHeatMapData = ref()
  const timeHeatMapData = ref()
  const dateArray = ref([]) // 收集calendar-change事件的回调日期
  const checkAll = ref(false)
  const indeterminate = ref(false)
  const exportLoading = ref(false)
  /* =============方法============== */
  const handleCheckAll = val => {
    indeterminate.value = false
    if (val) {
      queryForm.eventType = eventTypeList.value.map(_ => _.pkId)
    } else {
      queryForm.eventType = []
    }
  }
  const disabledDate = time => {
    let todayTimestamp = new Date(new Date().toLocaleDateString()).getTime()
    let max = Date.now() - 8.64e7
    if (dateArray.value.length === 0) {
      return time.getTime() >= todayTimestamp
    } else {
      return time.getTime() >= dateArray.value[0].getTime() + 31 * 8.64e7 || time.getTime() <= dateArray.value[0].getTime() - 31 * 8.64e7 || time.getTime() >= max
    }
  }
  const changeRange = date => {
    dateArray.value = date
  }
  const clearDateArray = () => {
    dateArray.value = []
  }
  const handleMenuClick = (menu, menuIndex) => {
    if (menuIndex === activeMenuIndex.value) {
      return
    }
    if (menuIndex === 1) {
      ruleFormRef.value.validate(valid => {
        if (valid) {
          getDetailListData()
        } else {
          console.log('error submit!')
          return false
        }
      })
    } else {
      queryAllData()
    }
    activeMenuIndex.value = menuIndex
  }
  const getBasicRegionData = async () => {
    try {
      const res = await proxy.$http.postWithBody('overview/region/list', { status: 1 })
      regionList.value = handleResRegionData(res)
      queryForm.regionArea = regionList.value[0].value
    } catch (error) {
      console.log(error)
    }
  }
  const handleResRegionData = nodes => {
    return nodes.map(node => {
      const newNode = {
        ...node,
        value: node.name,
        label: node.name
      }
      if (node.children) {
        newNode.children = handleResRegionData(node.children)
      }

      return newNode
    })
  }
  const getRankList = async () => {
    try {
      let reqData = {
        startDate: queryForm.dateRange[0],
        endDate: queryForm.dateRange[1],
        alarmTypes: queryForm.eventType
      }
      const res = await proxy.$http.postWithBody('alarm/points/rank', reqData)
      rankList.value = res
    } catch (error) {
      console.log(error)
    }
  }
  const getAlarmTypeList = async () => {
    try {
      eventTypeList.value = []
      const res = await proxy.$http.getFun('alarm/type')
      eventTypeList.value = res
      queryForm.eventType = res.map(_ => _.pkId)
    } catch (error) {
      console.log(error)
    }
  }
  const getSpaceHeatMap = async () => {
    try {
      let reqData = {
        startDate: queryForm.dateRange[0],
        endDate: queryForm.dateRange[1],
        alarmTypes: queryForm.eventType
      }
      const res = await proxy.$http.postWithBody('alarm/space/heatmap', reqData)
      spaceHeatMapData.value = res
    } catch (error) {
      console.log(error)
    }
  }
  const getTimeHeatMap = async () => {
    try {
      let reqData = {
        startDate: queryForm.dateRange[0],
        endDate: queryForm.dateRange[1],
        alarmTypes: queryForm.eventType
      }
      const res = await proxy.$http.postWithBody('alarm/time/heatmap', reqData)
      timeHeatMapData.value = res
    } catch (error) {
      console.log(error)
    }
  }
  const getEventComparisonList = async () => {
    try {
      let reqData = {
        startDate: queryForm.dateRange[0],
        endDate: queryForm.dateRange[1],
        alarmTypes: queryForm.eventType
      }
      const res = await proxy.$http.postWithBody('alarm/comparison', reqData)
      eventComparisonList.value = res
    } catch (error) {
      console.log(error)
    }
  }
  const getDetailListData = async () => {
    try {
      tableLoadingStatus.value = true
      let reqData = {
        startDate: queryForm.dateRange[0],
        endDate: queryForm.dateRange[1],
        alarmTypes: queryForm.eventType,
        pageNum: pageInfo.pageNum,
        pageSize: pageInfo.pageSize
      }
      const res = await proxy.$http.postWithBody('alarm/list', reqData)
      detailListData.value = res
      tableLoadingStatus.value = false
    } catch (error) {
      console.log(error)
      tableLoadingStatus.value = false
    }
  }
  const changePageNum = pageNum => {
    pageInfo.pageNum = pageNum
    getDetailListData()
  }
  const changePageSize = pageSize => {
    pageInfo.pageSize = pageSize
    pageInfo.pageNum = 1
    getDetailListData()
  }
  const exportData = async () => {
    try {
      exportLoading.value = true
      let data = {
        startDate: queryForm.dateRange[0],
        endDate: queryForm.dateRange[1],
        alarmTypes: queryForm.eventType
      }
      const excelRes = await proxy.$http.downExcel('alarm/export', data)
      if (excelRes) {
        let blob = new Blob([excelRes], {
          type: 'application/vnd.ms-excel;charset=UTF-8'
        })
        let zipUrl = window.URL.createObjectURL(blob)
        const alink = document.createElement('a')
        alink.download = `数据分析${data.startDate}至${data.endDate}详单表` + '.xls'
        alink.href = zipUrl
        alink.click()
        URL.revokeObjectURL(alink.href)
      }
      exportLoading.value = false
    } catch (error) {
      console.log(error)
      exportLoading.value = false
    }
  }
  const queryAllData = formEl => {
    if (!formEl) return
    formEl.validate(valid => {
      if (valid) {
        if (activeMenuIndex.value === 0) {
          getRankList()
          getEventComparisonList()
          getSpaceHeatMap()
          getTimeHeatMap()
        } else {
          getDetailListData()
        }
      } else {
        console.log('error submit!')
        return false
      }
    })
  }
  watch(
    () => queryForm.eventType,
    val => {
      if (val.length === 0) {
        checkAll.value = false
        indeterminate.value = false
      } else if (val.length === eventTypeList.value.length) {
        checkAll.value = true
        indeterminate.value = false
      } else {
        indeterminate.value = true
      }
    }
  )
  onMounted(async () => {
    getBasicRegionData()
    await getAlarmTypeList()
    getRankList()
    getEventComparisonList()
    getSpaceHeatMap()
    getTimeHeatMap()
  })
</script>

<style scoped lang="scss">
  .data-analysis {
    padding: pxTvh(18) pxTvw(24) pxTvh(24) pxTvw(24);
    display: flex;
    flex-direction: column;
    & > .search-wrapper {
      @include computed_font(14);
      color: #bed3e6;
      display: flex;
      align-items: center;
      padding: 0 pxTvw(16);
      box-sizing: border-box;
      height: pxTvh(88);
      margin: pxTvh(0) 0 pxTvh(16) 0;
      background: #0d172f;
      border-radius: 4px;
      & > .btn-group {
        margin-left: auto;
        margin-right: 0;
      }
    }
    & > .main-content-wrapper {
      height: 100%;
      overflow-y: scroll;
      & > .menu-bar {
        background-color: #0d172f;
        display: flex;
        align-items: center;
        height: pxTvh(50);
        border-bottom: 1px solid rgba(82, 92, 118, 0.5);
        color: #899cac;
        @include computed_font(14);
        width: calc(100% - #{pxTvw(48)});
        position: fixed;
        z-index: 99;
        & > .menu-item {
          cursor: pointer;
          padding: 0 pxTvw(24);
          height: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
          box-sizing: border-box;
          border-bottom: 2px solid transparent;
          &.menu-active {
            color: #377dff;
            border-bottom: 2px solid #377dff;
          }
        }
      }
    }
  }
</style>
